package fr.gdi.android.news;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import fr.gdi.android.news.utils.Constants;

public class FileChooserActivity extends ListActivity
{
    private String root;
    private File currentDir;
    private FileArrayAdapter adapter;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //currentDir = IOUtils.getFolder(IOUtils.EXTERNAL_STORAGE);
        currentDir = Environment.getExternalStorageDirectory();
        root = currentDir.getAbsolutePath();
        fill(currentDir);
    }
    
    private void fill(File f)
    {
        File[] dirs = f.listFiles();
        this.setTitle("Choose a file - current directory: " + f.getName());
        List<FileChooserOption> dir = new ArrayList<FileChooserOption>();
        List<FileChooserOption> fls = new ArrayList<FileChooserOption>();
        try
        {
            for (File ff : dirs)
            {
                if (ff.isDirectory())
                    dir.add(new FileChooserOption(ff.getName(), "Folder", ff.getAbsolutePath()));
                else
                {
                    fls.add(new FileChooserOption(ff.getName(), "File Size: " + ff.length() + " bytes", ff.getAbsolutePath()));
                }
            }
        }
        catch (Exception e)
        {
            
        }
        Collections.sort(dir);
        Collections.sort(fls);
        dir.addAll(fls);
        if (!TextUtils.equals(f.getAbsolutePath(), root)) dir.add(0, new FileChooserOption("..", "Parent Directory", f.getParent()));
        adapter = new FileArrayAdapter(FileChooserActivity.this, R.layout.file_view, dir);
        this.setListAdapter(adapter);
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id)
    {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        FileChooserOption o = adapter.getItem(position);
        if (o.getData().equalsIgnoreCase("folder") || o.getData().equalsIgnoreCase("parent directory"))
        {
            currentDir = new File(o.getPath());
            fill(currentDir);
        }
        else
        {
            onFileClick(o);
        }
    }
    
    private void onFileClick(FileChooserOption o)
    {
        Intent resultValue = new Intent();
        resultValue.putExtra(Constants.FILENAME_KEY, o.getPath());
        setResult(RESULT_OK, resultValue);
        finish();
    }
}